; (function ($) {
    var login = $("#btn");
    var form = $("#loginForm");
    var userIpt = $("#userName");
    var pwdIpt = $("#userPassword");
    var cookie_user = getCookie("username");
    var cookie_pass = getCookie("password");
    if (cookie_user && cookie_pass) {
        userIpt.val(cookie_user);
        pwdIpt.val(cookie_pass);
    }


    function getCookie(key) {
        var _cookie = document.cookie;
        // "key=value; key2=value; key3=value";
        var _cookie_item = _cookie.split("; ");
        var _key = [];
        var _value = _cookie_item.map(item => {
            var _temp = item.split("=");
            _key.push(_temp[0]);
            return _temp[1];
        })
        var index = _key.indexOf(key);
        if (index !== -1) {
            return _value[index];
        }
        return "";
    }

    function jsonp(url, cb_key, data) {
        cb_key = !cb_key ? "callback" : cb_key;

        data = !data ? {} : data;
        return new Promise((resove, reject) => {
            var cb_name = "gp10" + Date.now();
            window[cb_name] = function (res) {
                resove(res);
            }
            var script = document.createElement("script");
            url += /\?/.test(url) ? "&" : "?";
            url += cb_key + "=" + cb_name;
            for (let key in data) {
                url += `&${key}=${data[key]}`;
            }
            script.src = url;
            document.body.appendChild(script);
            script.onload = function () {
                this.remove();
            }
        })
    }


    //阻止表单默认事件
    form.submit((evt) => {
        var e = evt || window.event;
        e.preventDefault();
    })
    login.click((evt) => {
        var username = userIpt.val();
        var password = pwdIpt.val();
        jsonp("http://localhost:80/GP10/project/login.php", "cb", {
            username: username,
            password: password
        })
            .then((res) => {
                res = JSON.parse(res);
                if (res["statu"] === "error") {
                    switch (res["stateCode"]) {
                        case ("2"): alert("登录失败");
                            break;
                        case ("5"): alert("此用户名还没注册");
                            break;
                    }
                    return;
                }
                if(res["statu"] === "success"){
                    alert("登陆成功！")
                    window.location.href="index.html"; 
                }
            })
    })
})(jQuery);

